import api from "../../utils/api"
import Utils from "../../utils/utils"

// pages/notice/notice.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: 1,
    pageSize: 10,
    totalCount: 0,
    isLoading: false,
    messageList: [] as MessageModel[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getMessageList()
  },
  getMessageList(): void {
    const { page, messageList, pageSize, isLoading } = this.data
    if (isLoading) {
      return
    }
    this.setData({
      isLoading: true
    })
    api.message.getMessageList({ page, pageSize }).then(res => {
      if (res.data.code == "000") {
        if (res.data.data && res.data.data.list) {
          res.data.data.list.forEach(item => {
            item.time = Utils.timestampToDateTime(item.time as number)
          })
          this.setData({
            messageList: [...messageList, ...res.data.data.list],
            totalCount: res.data.data.totalCount,
            page: page + 1
          })
        }
        this.setData({
          isLoading: false
        })
      } else {
        this.setData({
          isLoading: false
        })
        wx.showToast({
          title: res.data.message as string,
          icon: "error"
        })
      }
    })
  },
  read(e: any): void {
    const id = e.currentTarget.dataset.id;
    let message = e.currentTarget.dataset.message;
    console.log(id);
    api.message.readMessage({ id }).then(res => {
      if (res.data.code == "000") {
        this.data.messageList = this.data.messageList.map(item => {
          if (item.id == id) {
            return { ...item, read: true }
          } else {
            return item
          }
        })
        this.setData({
          messageList: this.data.messageList
        })
      } else {
        wx.showToast({
          title: res.data.message as string,
          icon: "error"
        })
      }
    }).finally(() => {
      if (message.type === 'REPORT') {
        wx.navigateTo({
          url:'/pages/report/report'
        })
      }
      if (message.type === 'TESTING') {
        wx.navigateTo({
          url:'/pages/progress/progress'
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    const { totalCount, messageList } = this.data
    if (totalCount == messageList.length) {
      return
    }
    this.getMessageList();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})